"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

require("antd/lib/modal/style/css");

var _modal = _interopRequireDefault(require("antd/lib/modal"));

var _react = _interopRequireWildcard(require("react"));

var _util = require("./util");

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var useFileFetch = function useFileFetch() {
  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

  var _useState3 = (0, _react.useState)(true),
      _useState4 = _slicedToArray(_useState3, 2),
      loading = _useState4[0],
      setLoading = _useState4[1];

  var _useState5 = (0, _react.useState)(''),
      _useState6 = _slicedToArray(_useState5, 2),
      fileLink = _useState6[0],
      setFileLink = _useState6[1];

  var fetchFile = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(fileURL) {
      var data;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              setVisible(true);
              _context.next = 3;
              return fetch(fileURL).then(function (res) {
                return res.ok && res.blob();
              });

            case 3:
              data = _context.sent;
              // eslint-disable-next-line no-unused-expressions
              data && setFileLink(window.URL.createObjectURL(data));
              setLoading(false);

            case 6:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function fetchFile(_x) {
      return _ref.apply(this, arguments);
    };
  }();

  var hiddenFile = function hiddenFile() {
    setVisible(false);
  };

  return {
    loading: loading,
    visible: visible,
    fetchFile: fetchFile,
    hiddenFile: hiddenFile,
    fileLink: fileLink
  };
};

function FullPreFile(props) {
  var visible = props.visible,
      loading = props.loading,
      hiddenFile = props.hiddenFile,
      viewName = props.viewName,
      fileLink = props.fileLink;
  var modalProps = (0, _react.useMemo)(function () {
    var name = viewName || '';
    var width = document.documentElement.clientWidth;
    return {
      width: width,
      visible: visible,
      loading: loading,
      footer: null,
      onOk: hiddenFile,
      onCancel: hiddenFile,
      title: "\u9884\u89C8- ".concat(name),
      wrapClassName: 'pre-view'
    };
  }, [loading, visible, hiddenFile, viewName]);
  var onLoad = (0, _react.useCallback)(function (e) {
    try {
      var content = e.currentTarget.contentWindow;
      var bodyIframe = content.document.body;
      bodyIframe.style.display = 'flex';
      bodyIframe.style.alignItems = 'center';
      bodyIframe.style.justifyContent = 'center';
    } catch (error) {
      console.log('非chrome浏览器 可能 ifrom document 获取方式API不同', error);
    }
  }, []);
  var iframeProps = (0, _react.useMemo)(function () {
    var height = document.documentElement.clientHeight;
    return {
      src: fileLink,
      onLoad: onLoad,
      align: 'center',
      frameBorder: '0',
      style: {
        width: '100%',
        display: 'flex',
        height: height
      }
    };
  }, [onLoad, fileLink]);
  return /*#__PURE__*/_react.default.createElement(_modal.default, _extends({}, modalProps, {
    destroyOnClose: true
  }), /*#__PURE__*/_react.default.createElement("iframe", _extends({
    title: "name"
  }, iframeProps)));
}

function PreFileView(props) {
  var viewUrl = props.viewUrl,
      viewId = props.viewId,
      viewCode = props.viewCode,
      viewName = props.viewName;

  var _useFileFetch = useFileFetch(),
      loading = _useFileFetch.loading,
      visible = _useFileFetch.visible,
      fetchFile = _useFileFetch.fetchFile,
      hiddenFile = _useFileFetch.hiddenFile,
      fileLink = _useFileFetch.fileLink;

  var fileURL = (0, _react.useMemo)(function () {
    if (viewUrl) return viewUrl;
    return (0, _util.createParamsUrl)({
      fileId: viewId,
      fileCode: viewCode
    }, 'download');
  }, [viewUrl, viewId, viewCode]);
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("a", {
    onClick: fetchFile.bind(null, fileURL),
    style: {
      marginRight: 8
    }
  }, "\u9884\u89C8"), /*#__PURE__*/_react.default.createElement(FullPreFile, {
    visible: visible,
    loading: loading,
    viewName: viewName,
    fileLink: fileLink,
    hiddenFile: hiddenFile
  }));
}

var _default = PreFileView;
exports.default = _default;